package com.easychat.test;

import org.springframework.http.converter.json.GsonBuilderUtils;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

public class SocketServer {
    public static void main(String[] args) {
        ServerSocket server = null;
        Map<String, Socket> CLIENT_MAP = new HashMap<>();
        try{
            server = new ServerSocket(1024);
            System.out.println("服务启动，等待客户端连接");
            while (true){
                Socket client = server.accept();
                String ip = client.getInetAddress().getHostAddress();
                System.out.println("有客户端链接ip:"+ip+",端口:"+client.getPort());
                String clientKey = ip + client.getPort();
                CLIENT_MAP.put(clientKey, client);

                new Thread(()->{
                    while (true){
                        try{
                            InputStream inputStream = client.getInputStream();
                            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
                            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                            String readData = bufferedReader.readLine();
                            System.out.println("客户端收到的消息->" + readData);

                            CLIENT_MAP.forEach((k,v)-> {
                                    try{
                                        OutputStream outputStream = v.getOutputStream();
                                        PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(outputStream, "UTF-8"));
                                        printWriter.println(client.getPort()+":"+ readData);
                                        printWriter.flush();
                                    }catch (Exception e){

                                    }
                            });

                        }catch (Exception e){

                        }
                    }
                }).start();
            }
        }catch (Exception e){
        }
    }
}
